//
//  TheMap.m
//  XiangMu
//
//  Created by 康世标 on 15/10/15.
//  Copyright (c) 2015年 康世标. All rights reserved.
//

#import "TheMap.h"

@interface TheMap ()

@end

@implementation TheMap

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.arr = [[NSMutableArray alloc]initWithCapacity:0];
    
    self.titArr = [[NSArray alloc]initWithArray:0];

    [self initMapView];
//    [self initTableView];
    [self initBtn];
    [self initBarButon];
}
- (void)initBarButon{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(btn)];
    
}
- (void)btn{
    
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0]];
    
    NSLog(@"---%@",cell.detailTextLabel.text);
    
   
    
    if (self.block) {
        
        self.block([NSString stringWithFormat:@"%@%@",cell.detailTextLabel.text,cell.textLabel.text]);
        
      
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)initBtn{
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame = CGRectMake(10, self.myView.frame.size.height+self.myView.frame.origin.y-40, 20, 20);
    
    [btn setImage:[UIImage imageNamed:@"locate@2x"] forState:UIControlStateNormal];
    
     [btn addTarget:self action:@selector(btnClock) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:btn];
    
}
- (void)btnClock{
    
    
    [_mapview setCenterCoordinate:CLLocationCoordinate2DMake(self.latitude, self.longitude) animated:YES];
    
    
}

- (void)initMapView{
    [MAMapServices sharedServices].apiKey = KEY;
    _search = [[AMapSearchAPI alloc] initWithSearchKey:KEY Delegate:self];
    
    _search.language = 1;
    
    
    _mapview = [[MAMapView alloc] initWithFrame:self.myView.frame];
    _mapview.delegate = self;
    
    
    //开启定位
    _mapview.mapType = MAMapTypeStandard;
    
    _mapview.showsUserLocation = YES;
    _mapview.language = MAMapLanguageZhCN ;
    
    _mapview.userTrackingMode = MAUserTrackingModeFollow;
    
    //    [_mapview setUserInteractionEnabled:YES];
    _mapview.userTrackingMode = 1;
    //为了使地图精准
    _mapview.desiredAccuracy =kCLLocationAccuracyBest;
    //定位图层
    //    [_mapview setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
    //地图    缩放级别
    [_mapview setZoomLevel:15.5 animated:YES];
    //自定义精度圈 必须先设置YES
    //    _mapview.customizeUserLocationAccuracyCircleRepresentation = YES;
    //后台挂起  继续定位
    //    _mapview.pausesLocationUpdatesAutomatically = YES;
    // 设置成NO表示关闭指南针；YES表示显示指南针
    _mapview.showsCompass= YES;
    
    _mapview.compassOrigin= CGPointMake(_mapview.compassOrigin.x, 84);
    //设置成NO表示不显示比例尺；YES表示显示比例尺
    _mapview.showsScale= NO;
    _mapview.scaleOrigin= CGPointMake(_mapview.scaleOrigin.x, 84);  //设置比例尺位置
    //手势的开关               NO表示禁用缩放手势，YES表示开启
    _mapview.zoomEnabled = YES;
    //滑动手势，YES表示开启
    _mapview.scrollEnabled = YES;
    //旋转手势，YES表示开启
    //    _mapview.rotateEnabled= YES;
    [self.myView addSubview:_mapview];
    
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titArr.count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * inenf = @"";
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:inenf];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:inenf];
        
      

    }
    AMapPOI * poi =self.titArr[indexPath.row];
    
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@%@",self.add.province,self.add.city,self.add.district,poi.address];
    
  
    if (self.index==indexPath.row)
    {
        
       cell.accessoryType = UITableViewCellAccessoryCheckmark;

    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        
    }
    
    
    return cell;

}
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 取消前一个选中的，就是单选啦
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_index inSection:0];
    UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
    lastCell.accessoryType = UITableViewCellAccessoryNone;
    
    // 选中操作
    UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    
    // 保存选中的
    
    _index = indexPath.row;
    
    AMapPOI * poi =self.titArr[indexPath.row];
    
    MAPointAnnotation * point = [[MAPointAnnotation alloc]init];
    
    point.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    point.title = poi.name;
    point.subtitle = poi.address;
    
    [self.arr addObject:point];
    
    for (MAPointAnnotation * a in self.arr)
    {
        
        [_mapview removeAnnotation:a];
        
    }
    [_mapview setCenterCoordinate:CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude) animated:YES];
    
    [_mapview addAnnotation:point];
    
    
}


#pragma mark --- MAMapViewDelegate
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        static NSString * reuse = @"s";
        MAAnnotationView * annonta = (MAPinAnnotationView *)[_mapview dequeueReusableAnnotationViewWithIdentifier:reuse];
        
        if (annonta==nil) {
            
            annonta = [[MAPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:reuse];
            
        }
        
        annonta.canShowCallout = YES;
        
        return annonta;
        
    }
    return nil;
}
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        
        self.longitude =userLocation.coordinate.longitude;
        self.latitude = userLocation.coordinate.latitude;
        
        _mapview.delegate = nil;
        if (_search ==nil) {
            
            return;
        }
        
    
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude     longitude:userLocation.coordinate.longitude];
        regeo.radius = 10000;
        
        regeo.requireExtension = YES;
        
        //发起逆地理编码
        [_search AMapReGoecodeSearch: regeo];
      
    }
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    
    
    
    self.add = response.regeocode.addressComponent;
    
    self.titArr = response.regeocode.pois;
    
    [self.tableView reloadData];
    
    
    AMapPOI * poi =self.titArr[0];
    
    MAPointAnnotation * point = [[MAPointAnnotation alloc]init];
    
    point.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    point.title = poi.name;
    point.subtitle = poi.address;
    
    [self.arr addObject:point];
    
    
    [_mapview addAnnotation:point];
}
- (void)dealloc{
    
    _mapview.delegate = nil;
    _search.delegate = nil;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
